package com.example.demo.Service;

import com.example.demo.Convert.CurrentWarehouse;
import com.example.demo.Convert.InfoForGraph1;
import com.example.demo.Entity.*;
import com.example.demo.Repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Type;
import java.util.*;

import java.util.Optional;

@Service
public class ItemServiceImpl implements ItemService {

    private final ItemRepo itemRepository;
    private final CurrentStorageRepo currentStorageRepo;
    private final OperationLogRepo operationLogRepo;
    private final ShelfRepo shelfRepo;
    private final WarehouseRepo warehouseRepo;

    @Autowired
    public ItemServiceImpl(ItemRepo itemRepository,
                           CurrentStorageRepo currentStorageRepo,
                           OperationLogRepo operationLogRepo,
                           ShelfRepo shelfRepo,
                           WarehouseRepo warehouseRepo) {
        this.itemRepository = itemRepository;
        this.currentStorageRepo = currentStorageRepo;
        this.operationLogRepo = operationLogRepo;
        this.shelfRepo = shelfRepo;
        this.warehouseRepo = warehouseRepo;
    }

    @Override
    public Item createItem(Item item) {
        item.setCreatedAt(new Date());
        item.setUpdatedAt(new Date());
        return itemRepository.save(item);
    }

    @Override
    public Optional<Item> getItemById(Long id) {
        return itemRepository.findById(id);
    }

    @Override
    public Optional<Item> getItemByName(String name) { return itemRepository.findByName(name); }

    @Override
    public Map<String, Object> searchDistribution(Item theItem) {//某个物品在各个仓库的分布情况
        Optional<Item> item = getItemByName(theItem.getName());

        Map<String, Object> response = new HashMap<>();
        if(item.isPresent()){

            List<CurrentStorage> storageList = currentStorageRepo.findByItem(item.get());//现存的该货物的列表

            InfoForGraph1 infoForGraph1 = new InfoForGraph1();

            List<CurrentWarehouse> list = new ArrayList<>();

            for (CurrentStorage currentStorage : storageList) {//匹配仓库和item的数量关系
                CurrentWarehouse currentWarehouse = new CurrentWarehouse();
                currentWarehouse.setWarehouseName(currentStorage.getWarehouse().getName());
                currentWarehouse.setQuentity(currentStorage.getCurrentQuantity());

                list.add(currentWarehouse);
            }

            infoForGraph1.setItemName(item.get().getName());
            infoForGraph1.setCurrentWarehouse(list);

            response.put("success",true);
            response.put("message","查找成功");
            response.put("itemDistribution",infoForGraph1);

        }else {
            response.put("success",false);
            response.put("message","该物品不存在");
        }
        return response;
    }

    @Override
    public Map<String, Object> intelligence(Item theItem) {
        Optional<Item> itemOptional = this.getItemByName(theItem.getName());

        Map<String, Object> response = new HashMap<>();
        double epsilon = 1e-10; // 自定义无穷小量，可以根据需要调整epsilon的值

        if(itemOptional.isPresent()){
            Item item1 = itemOptional.get();
            long itemId = item1.getId();
            //先查找最近一个星期时间的出库记录总和
            Date now = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            calendar.add(Calendar.WEEK_OF_YEAR, -1);
            Date oneWeekAgo = calendar.getTime();
            List<OperationLog> logs = operationLogRepo.findOutgoingLogsForItemBetweenDates(itemId, oneWeekAgo, now);
            double chuku = 0;
            for (OperationLog log : logs) {
                chuku += log.getQuantity();
            }
            //再查找当前该物品剩余总和
            Item item = item1;
            List<CurrentStorage> storages = currentStorageRepo.findByItem(item);
            double current = 0;
            for (CurrentStorage storage : storages) {
                current += storage.getCurrentQuantity();
            }

            response.put("success",true);

            if(Math.abs(chuku) > epsilon){
                if(current/chuku > 2){//剩余可支持两个星期
                    response.put("message",item.getName()+"库存"+current+"kg，剩余量充足，暂时无需补充");
                }else if  (current/chuku > 1){
                    response.put("message",item.getName()+"库存"+current+"kg，剩余量较少，可以适当补充");
                }else{
                    response.put("message",item.getName()+"库存"+current+"kg，剩余量很少，急需马上补充");
                }
            }else{//出库量为0
                if(Math.abs(current) > epsilon){
                    response.put("message",item.getName()+"库存"+current+"kg，暂无出库需求，无需补充");
                }else {
                    response.put("message",item.getName()+"已无库存，急需马上补充");
                }
            }

        }else{
            response.put("success",false);
            response.put("message","查找失败：该物品不存在");
        }
        return response;
    }

    @Override
    public List<Item> getAllItems() {
        return itemRepository.findAll();
    }

    @Override
    public Map<String,Object> updateItem(Long id, Item item) {
        Optional<Item> existingItemOptional = itemRepository.findById(id);
        Map<String, Object> response = new HashMap<>();
        if (existingItemOptional.isPresent()) {
            Item existingItem = existingItemOptional.get();
            existingItem.setName(item.getName());
            existingItem.setCategory(item.getCategory());
            existingItem.setWeight(item.getWeight());
            existingItem.setUpdatedAt(new Date());
            itemRepository.save(existingItem);
            response.put("success",true);
            response.put("message", "物品更新成功");
            return response;
        } else {
            response.put("success",false);
            response.put("message","物品不存在");
            return response; // Or throw an exception
        }
    }

    @Override
    public Item saveItem(Item item) {
        return itemRepository.save(item);
    }

    @Override
    public Map<String, Object> updateItemByName(String name, String newCategory, String newName){
        Optional<Item> t = getItemByName(name);
        Map<String, Object> response = new HashMap<>();
        if(t.isEmpty()){
            response.put("success",false);
            response.put("message","物品不存在");
            return response;
        }else {
            response.put("success",true);
            t.get().setName(newName);
            t.get().setCategory(newCategory);
            response.put("message", "传输成功");
            response.put("Item",t.get());
            return response;
        }
    }

    @Override
    public void updateByCurrentstorage(double weight, CurrentStorage currentStorage, User user) {
        //更新log
        Warehouse warehouse = currentStorage.getWarehouse();
        int size = warehouse.getShelves().size();
        Shelf shelf ;
        if(size > 0){
            shelf = warehouse.getShelves().get(size-1);
        }else {
            Random random = new Random();
            int randomNumber = random.nextInt(2) + 1;
            shelf = shelfRepo.getById((long) randomNumber);
        }

        OperationLog log = new OperationLog();
        log.setWarehouse(warehouse);
        log.setItem(currentStorage.getItem());
        log.setShelf(shelf);
        log.setUser(user);
        log.setIsRuku(false);
        log.setQuantity(weight);
        operationLogRepo.save(log);

        //更新current
        if (weight > currentStorage.getCurrentQuantity()) {
            currentStorage.setCurrentQuantity((double) 0);
        } else {
            currentStorage.setCurrentQuantity(currentStorage.getCurrentQuantity()-weight);
        }
        currentStorageRepo.save(currentStorage);

        //更新货架
        if (shelf != null) {
            if(weight > shelf.getCurrentStorage()){
                shelf.setCurrentStorage((double) 0);
            }else {
                shelf.setCurrentStorage(shelf.getCurrentStorage()-weight);
            }
            shelfRepo.save(shelf);
        }

        //更新仓库
        warehouse.setCurrentStorage(warehouse.getCurrentStorage()-weight);
        warehouseRepo.save(warehouse);
    }

    @Override
    public Map<String,Object> deleteItem(Long id) {
        Map<String, Object> response = new HashMap<>();
        if (itemRepository.existsById(id)) {
            itemRepository.deleteById(id);
            response.put("success",true);
            response.put("message", "物品删除成功");
            return response;
        } else {
            response.put("success",false);
            response.put("message","物品不存在");
            return response; // Or throw an exception
        }
    }
}

